package com.example.myapplication.frament.dynasty;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.DynastyDialog;
import com.example.myapplication.R;

public class Introduction extends Fragment {

    private WebView webView;

    @SuppressLint("JavascriptInterface")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getContext() , R.layout.dynasty_introduction , null);
        webView = view.findViewById(R.id.introduction_webview);
        String content = DynastyDialog.getContent();
        if (content.equals("秦")){
            webView.loadUrl("https://baike.baidu.com/item/"+content+"国");
        }else{
            webView.loadUrl("https://baike.baidu.com/item/"+content+"朝");
        }
        webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                webView.stopLoading();
                webView.clearView();

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
                        + "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            }
        });
        return view;
    }
    final class InJavaScriptLocalObj {
        public void showSource(String html) {
            if (html.contains("sorry")){
//                webView.clearView();
//                webView.loadUrl("file:///android_asset/err.html");
            }
        }
    }
}
